<template>
  <Dialog v-model="dialogVisible" title="考生签到" width="600px">
    <el-form
      ref="formRef"
      :model="checkInForm"
      :rules="checkInRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 考生信息 -->
      <el-divider content-position="left">考生信息</el-divider>
      <el-form-item label="考生查找" prop="candidateSearch">
        <el-input
          v-model="checkInForm.candidateSearch"
          placeholder="请输入考生姓名、身份证号或准考证号"
          @input="searchCandidate"
          clearable
        >
          <template #append>
            <el-button @click="searchCandidate">搜索</el-button>
          </template>
        </el-input>
      </el-form-item>
      
      <!-- 搜索结果 -->
      <div v-if="candidateList.length > 0" style="margin-bottom: 20px;">
        <el-table :data="candidateList" @row-click="selectCandidate" style="cursor: pointer;">
          <el-table-column prop="candidateName" label="姓名" width="120" />
          <el-table-column prop="idCard" label="身份证号" width="180" />
          <el-table-column prop="examNo" label="准考证号" width="150" />
          <el-table-column prop="professionName" label="评价职业" />
          <el-table-column prop="examTime" label="考试时间" />
        </el-table>
      </div>
      
      <!-- 已选考生信息 -->
      <div v-if="selectedCandidate">
        <el-descriptions :column="2" border style="margin-bottom: 20px;">
          <el-descriptions-item label="考生姓名">
            {{ selectedCandidate.candidateName }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证号">
            {{ selectedCandidate.idCard }}
          </el-descriptions-item>
          <el-descriptions-item label="准考证号">
            {{ selectedCandidate.examNo }}
          </el-descriptions-item>
          <el-descriptions-item label="评价职业">
            {{ selectedCandidate.professionName }}
          </el-descriptions-item>
          <el-descriptions-item label="考试场次">
            {{ selectedCandidate.examSession }}
          </el-descriptions-item>
          <el-descriptions-item label="座位号">
            {{ selectedCandidate.seatNo }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <!-- 签到信息 -->
      <el-divider content-position="left">签到信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="签到时间" prop="checkInTime">
            <el-date-picker
              v-model="checkInForm.checkInTime"
              type="datetime"
              placeholder="选择签到时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签到状态" prop="checkInStatus">
            <el-radio-group v-model="checkInForm.checkInStatus">
              <el-radio value="normal">正常签到</el-radio>
              <el-radio value="late">迟到签到</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="签到方式" prop="checkInMethod">
            <el-select v-model="checkInForm.checkInMethod" placeholder="请选择签到方式">
              <el-option label="手动签到" value="manual" />
              <el-option label="扫码签到" value="qrcode" />
              <el-option label="刷卡签到" value="card" />
              <el-option label="人脸识别" value="face" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签到地点" prop="checkInLocation">
            <el-input v-model="checkInForm.checkInLocation" placeholder="请输入签到地点" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 身份验证 -->
      <el-divider content-position="left">身份验证</el-divider>
      <el-form-item label="身份验证" prop="identityVerification">
        <el-checkbox-group v-model="checkInForm.identityVerification">
          <el-checkbox label="id_card">身份证核验</el-checkbox>
          <el-checkbox label="face_recognition">人脸识别</el-checkbox>
          <el-checkbox label="fingerprint">指纹识别</el-checkbox>
          <el-checkbox label="signature">签名确认</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item label="体温检测" prop="temperatureCheck">
        <el-switch v-model="checkInForm.temperatureCheck" />
        <el-input-number
          v-if="checkInForm.temperatureCheck"
          v-model="checkInForm.temperature"
          :min="35"
          :max="42"
          :precision="1"
          style="margin-left: 10px; width: 120px;"
        />
        <span v-if="checkInForm.temperatureCheck" style="margin-left: 5px;">°C</span>
      </el-form-item>
      
      <el-form-item label="健康状况" prop="healthStatus">
        <el-radio-group v-model="checkInForm.healthStatus">
          <el-radio value="normal">正常</el-radio>
          <el-radio value="fever">发热</el-radio>
          <el-radio value="cough">咳嗽</el-radio>
          <el-radio value="other">其他异常</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item 
        label="异常说明" 
        prop="healthDescription" 
        v-if="checkInForm.healthStatus !== 'normal'"
      >
        <el-input
          v-model="checkInForm.healthDescription"
          type="textarea"
          :rows="2"
          placeholder="请描述具体症状"
        />
      </el-form-item>
      
      <!-- 物品检查 -->
      <el-divider content-position="left">物品检查</el-divider>
      <el-form-item label="携带物品检查" prop="itemsCheck">
        <el-checkbox-group v-model="checkInForm.itemsCheck">
          <el-checkbox value="no_phone">无手机等电子设备</el-checkbox>
          <el-checkbox value="no_books">无书籍资料</el-checkbox>
          <el-checkbox value="no_prohibited">无违禁物品</el-checkbox>
          <el-checkbox value="tools_allowed">允许携带工具</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item label="特殊情况" prop="specialSituation">
        <el-select v-model="checkInForm.specialSituation" placeholder="请选择特殊情况" clearable>
          <el-option label="无特殊情况" value="" />
          <el-option label="身体不适" value="illness" />
          <el-option label="证件问题" value="document_issue" />
          <el-option label="座位调整" value="seat_change" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      
      <el-form-item 
        label="情况说明" 
        prop="situationDescription" 
        v-if="checkInForm.specialSituation"
      >
        <el-input
          v-model="checkInForm.situationDescription"
          type="textarea"
          :rows="3"
          placeholder="请详细说明特殊情况"
        />
      </el-form-item>
      
      <el-form-item label="签到备注" prop="checkInRemark">
        <el-input
          v-model="checkInForm.checkInRemark"
          type="textarea"
          :rows="2"
          placeholder="请输入签到备注信息"
        />
      </el-form-item>
      
      <!-- 照片采集 -->
      <el-form-item label="现场照片">
        <el-upload
          :limit="3"
          :auto-upload="false"
          :on-change="handlePhotoUpload"
          accept=".jpg,.jpeg,.png"
          list-type="picture-card"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">支持jpg/png格式，最多3张</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="submitCheckIn" type="primary" :loading="formLoading">确认签到</el-button>
      <el-button @click="printCheckInSlip" type="success">打印签到单</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()

const selectedCandidate = ref(null)
const candidateList = ref([])

const checkInForm = ref({
  candidateSearch: '',
  candidateId: '',
  checkInTime: '',
  checkInStatus: 'normal',
  checkInMethod: 'manual',
  checkInLocation: '考场A',
  identityVerification: [] as string[],
  temperatureCheck: false,
  temperature: 36.5,
  healthStatus: 'normal',
  healthDescription: '',
  itemsCheck: [] as string[],
  specialSituation: '',
  situationDescription: '',
  checkInRemark: '',
  photos: [] as any[]
})

const checkInRules = ref({
  candidateSearch: [{ required: true, message: '请搜索并选择考生', trigger: 'blur' }],
  checkInTime: [{ required: true, message: '请选择签到时间', trigger: 'change' }],
  checkInStatus: [{ required: true, message: '请选择签到状态', trigger: 'change' }],
  checkInMethod: [{ required: true, message: '请选择签到方式', trigger: 'change' }],
  checkInLocation: [{ required: true, message: '请输入签到地点', trigger: 'blur' }],
  healthStatus: [{ required: true, message: '请选择健康状况', trigger: 'change' }],
  identityVerification: [
    { required: true, message: '请至少选择一种身份验证方式', trigger: 'change' }
  ]
})

const searchCandidate = () => {
  if (!checkInForm.value.candidateSearch.trim()) {
    candidateList.value = []
    return
  }
  
  // TODO: 实际搜索考生
  candidateList.value = [
    {
      id: 1,
      candidateName: '张三',
      idCard: '123456789012345678',
      examNo: 'EX202312001',
      professionName: '电工',
      examTime: '2023-12-15 09:00:00',
      examSession: '第一场次',
      seatNo: 'A001'
    },
    {
      id: 2,
      candidateName: '李四',
      idCard: '123456789012345679',
      examNo: 'EX202312002',
      professionName: '焊工',
      examTime: '2023-12-15 09:00:00',
      examSession: '第一场次',
      seatNo: 'A002'
    }
  ].filter(candidate => 
    candidate.candidateName.includes(checkInForm.value.candidateSearch) ||
    candidate.idCard.includes(checkInForm.value.candidateSearch) ||
    candidate.examNo.includes(checkInForm.value.candidateSearch)
  )
}

const selectCandidate = (candidate: any) => {
  selectedCandidate.value = candidate
  checkInForm.value.candidateId = candidate.id
  checkInForm.value.candidateSearch = candidate.candidateName
  candidateList.value = []
  
  // 设置默认签到时间为当前时间
  checkInForm.value.checkInTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
}

const handlePhotoUpload = (file: any, fileList: any[]) => {
  checkInForm.value.photos = fileList
}

const submitCheckIn = async () => {
  if (!selectedCandidate.value) {
    ElMessage.warning('请先搜索并选择考生')
    return
  }
  
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  
  formLoading.value = true
  try {
    const checkInData = {
      candidateId: selectedCandidate.value.id,
      candidateName: selectedCandidate.value.candidateName,
      examNo: selectedCandidate.value.examNo,
      ...checkInForm.value
    }
    
    // TODO: 提交签到数据
    console.log('考生签到:', checkInData)
    
    dialogVisible.value = false
    emit('success')
    ElMessage.success(`${selectedCandidate.value.candidateName} 签到成功`)
  } finally {
    formLoading.value = false
  }
}

const printCheckInSlip = () => {
  if (!selectedCandidate.value) {
    ElMessage.warning('请先完成签到')
    return
  }
  
  // TODO: 打印签到单
  ElMessage.info('签到单打印功能开发中...')
}

const resetForm = () => {
  checkInForm.value = {
    candidateSearch: '',
    candidateId: '',
    checkInTime: '',
    checkInStatus: 'normal',
    checkInMethod: 'manual',
    checkInLocation: '考场A',
    identityVerification: [],
    temperatureCheck: false,
    temperature: 36.5,
    healthStatus: 'normal',
    healthDescription: '',
    itemsCheck: [],
    specialSituation: '',
    situationDescription: '',
    checkInRemark: '',
    photos: []
  }
  
  selectedCandidate.value = null
  candidateList.value = []
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const open = () => {
  dialogVisible.value = true
  resetForm()
}

defineExpose({ open })
</script> 